<?php
namespace app\api\logic;

use app\common\model\XiluhouseSubwayPlatform;
use app\common\model\xiluhouse\Rental;
use app\common\model\xiluhouse\RentalRequest;
use app\common\model\xiluhouse\Village;

class SubwayPlatformLogic
{
    public function getList($params)
    {
        $where = [];
        if (!empty($params['keywords'])) {
            $where['name'] = ['like', '%' . $params['keywords'] . '%'];
        }

        $fields = ['id', 'name', 'code', 'lng', 'lat', 'subways'];
        $data = XiluhouseSubwayPlatform::where($where)->field($fields)->order('code asc')->select();

        // 默认type为1(房源)
        $type = isset($params['type']) ? intval($params['type']) : 1;
        
        // 总数量
        $total = 0;

        if ($data) {
            foreach ($data as $k => $v) {
                if ($type == 1) {
                    // 统计房源数量 - 通过小区关联
                    $count = Rental::alias('r')
                        ->join('xiluhouse_village v', 'r.village_id = v.id')
                        ->where('v.subway_platform_id', $v['id'])
                        ->where('r.status', 'normal')
                        ->where('r.deletetime', null)
                        ->where('r.apply_status', 1)
                        ->where('v.status', 'normal')
                        ->where('v.deletetime', null)
                        ->where('v.check_status', 1)
                        ->count();
                } else {
                    // 统计求租信息数量
                    $count = RentalRequest::where('metro_station_id', $v['id'])
                        ->where('status', 'normal')
                        ->where('is_delete', 2)
                        ->where('apply_status', 1)
                        ->count();
                }
                
                $data[$k]['count'] = $count;
                $total += $count;
            }
        }

        $result = [
            'total' => $total,
            'list' => $data,
        ];
        
        return $result;
    }
} 